package com.lyq.interaction.service;

import com.lyq.interaction.mapper.MessageMapper;
import com.lyq.interaction.mapper.SessionMessageMapper;
import com.lyq.interaction.mapper.UserMapper;
import com.lyq.interaction.model.Message;
import com.lyq.interaction.model.SessionMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SessionService {
    @Autowired
    private SessionMessageMapper sessionMessageMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户id获取所有会话
     * @param userId
     * @return 会话列表
     */
    public List<SessionMessage> getMessageSession(Integer userId) {
        //获取所有和当前用户有关的会话id和名字
        List<Integer> sessionIds = sessionMessageMapper.getSessionIdByUserId(userId);
        //获取这些会话中的好友信息（排除自己）
        List<SessionMessage> ret = new ArrayList<>();
        for (Integer id : sessionIds) {
            SessionMessage sessionMessage = new SessionMessage();
            sessionMessage.setSessionId(id);
            sessionMessage.setName(sessionMessageMapper.getSessionNameBySessionId(id));
            sessionMessage.setFriend(sessionMessageMapper.getSessionBySessionId(id, userId));
            Message lastMessage = messageMapper.getNewMessage(id);
            if (lastMessage != null) {
                sessionMessage.setLastMessage(lastMessage.getContent());
                sessionMessage.setType(lastMessage.getType());
            } else {
                sessionMessage.setLastMessage("");
            }
            ret.add(sessionMessage);
        }
        return ret;
    }

    //创建会话并返回会话id
    @Transactional
    public Object createSession(List<Integer> friendIds) {
        String sessionName = "";
        //如果是群聊
        if (friendIds.size() > 2) {
            //设置会话名（默认为好友名，长度不超过15）
            for (Integer id : friendIds) {
                sessionName += userMapper.getNameById(id);
                if (sessionName.length() > 15) {
                    sessionName = sessionName.substring(0, 15) + "...";
                }
            }
        }
        //创建会话
        SessionMessage sessionMessage = new SessionMessage();
        sessionMessage.setName(sessionName);
        sessionMessageMapper.insertSession(sessionMessage);
        //创建会话和用户的关系
        for (Integer friendId : friendIds) {
            sessionMessageMapper.insertUserFriend(friendId, sessionMessage.getSessionId());
        }
        return sessionMessage;
    }
}
